package cn.bs.allensocket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by Allen on 2014/10/31.
 */
public class AllenDatagramSocketServer {
    static int port = 7200;//与int port区别 只有在第一装载时才去初始化，而且早与变量所在类。int port只有在new类变量时才初始化
    private byte[] buf = new byte[1000];
    //自动完成import setting ->Editor ->Auto->select all
    private DatagramPacket db = new DatagramPacket(buf,buf.length);
    private DatagramSocket socket;

    public AllenDatagramSocketServer() throws IOException {
        System.out.println("start.....Server");
        socket = new DatagramSocket (port, InetAddress.getLocalHost());
        while(true)
        {
            socket.receive(db);
            System.out.println(new String(buf,0,db.getLength()));//使用了String的构造方法
            String rcdb = AllenDgram.toString(db) + ",from address:" + db.getAddress() + ",port:" + db.getPort();
            System.out.println(rcdb);
            String str = "Server:" + rcdb;

            DatagramPacket echodp = AllenDgram.toDataGram(str,db.getAddress(),db.getPort());
            socket.send(echodp);
        }
    }

}

